<?php
namespace Admin\Controller;
use Lib\Api\OrderApi;
use Lib\Api\RechargeWithdrawalsApi;
use Lib\Api\TradeDetailApi;
use Lib\Api\UserApi;
use Lib\Api\UserBelongApi;
use Lib\Utils\Utils;
use Think\Controller;
use Think\Model;

class UserController extends Controller {
    private $modelName = 'User';

    public function index(){
        /*$modelObj = M("Game_type");
        $list = $modelObj->where(array("state"=>1))->select();
        if (!empty($list) && count($list) > 0) {
            $this->assign('games',$list);
        }
        $modelObj = M("VoucherType");
        $list = $modelObj->select();
        if (!empty($list) && count($list) > 0) {
            $this->assign('voucher_type_list',$list);
        }*/

        $organization_id = session('admin_id');

        $modelObj = M();
        $min_date = $modelObj->table("fs_user a")->field('DATE_FORMAT(a.datetime, "%Y-%m-%d") as datetime')->join("left join fs_user_belong b on b.user_id = a.id")->where(array("b.organization_id"=>$organization_id))->page(1,1)->find();

        $datetime = date("Y-m-d");
        if (!empty($min_date['datetime'])) {
            $datetime = $min_date['datetime'];
        }
        $this->assign('d', $datetime);
        $this->display();
    }

    // 生成二维码
    public function q(){
        $modelObj = M($this->modelName);
        $data = $modelObj->field("type, code")->where(array('id' => $_GET['user_id']))->find();
        // if ($data["type"] == 3) {}
        $code = $data["code"];

        // $domain_url = C('TMPL_PARSE_STRING.__DOMAINURL__');
        // $web_site_dir = C('TMPL_PARSE_STRING.__WEBSITEDIR__');
        $modelObj = M('Sys');
        $data = $modelObj->field("qrcode_url")->where(array('id' => 1))->find();
        $url = str_replace("{#code}",$code,$data['qrcode_url']);
        qrcode($url,9);
    }

    // 全局搜索用户
    public function select_search() {
        $keyword = $_POST['keyword'];
        $list = [];
        if ($keyword <> "") {
            $where['mobile_phone'] = array('like', '%'.$keyword.'%');
            $where['real_name'] = array('like', '%'.$keyword.'%');
            $where['nick_name'] = array('like', '%'.$keyword.'%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;

            $modelObj = M($this->modelName);
            $list = $modelObj->where($map)->select();
        }
        $rel["list"] = $list;
        $this->ajaxReturn($rel);
    }

    // 获取用户列表
    public function tolist() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];

        $data_cycle = $_POST['data_cycle'];
        $nick_name = $_POST['nick_name'];
        $mobile_phone = $_POST['mobile_phone'];
        $agent_id = $_POST['agent_id'];
        $belong_organization_id = $_POST['organization_id'];
		
		$sortKey = $_POST['sortKey'];
        $sort = $_POST['sort'];


        $organization_id = session('admin_id');
        // $level = 0;
        $field = "a.id, a.recommend_id, ifnull(a.nick_name, '--') as nick_name, a.mobile_phone, a.balance, a.state, a.is_deall_order, ifnull(a.login_ip, '--') as login_ip, ifnull(a.last_login, '--') as last_login, a.datetime, ifnull(agent.name, '--') as agent_name, (a.recharge-a.withdrawals) recharge";

        $left = 'left join fs_user_belong b on b.user_id = a.id and b.state=1';
        $left .= ' left join fs_agent agent on agent.id = a.recommend_id';
        $AGENTCONFIG = C('AGENTCONFIG');
        for($i=1; $i<(count($AGENTCONFIG)-2); $i++) {
            $field .= ',ifnull(o'.$i.'.name, "--") as '.$AGENTCONFIG[$i]['field'];
            $left .= ' left join fs_user_belong ob'.$i.' on ob'.$i.'.user_id = a.id and ob'.$i.'.state = 1 and ob'.$i.'.organization_level = '.$i . ' and ob'.$i.'.state=1';
            $left .= ' left join fs_organization o'.$i.' on o'.$i.'.id = ob'.$i.'.organization_id';
        }

        $where_and_arr = array();
        $where_or_arr = array();

        $map = array();
        if ($nick_name != "") {
            $map['a.nick_name']  = array('like', '%'.$nick_name.'%');

            $where_or_arr[] = "a.nick_name like '%".$nick_name."%'";

        }
        if ($mobile_phone != "") {
            $map['a.mobile_phone']  = array('like', '%'.$mobile_phone.'%');

            $where_or_arr[] = "a.mobile_phone like '%".$mobile_phone."%'";
        }
        if ($agent_id > 0) {
            $map['a.recommend_id']  = array('eq', $agent_id);
            $where_or_arr[] = "a.recommend_id = ".$agent_id;
        } else if ($belong_organization_id != '') {
            $map['b.organization_id']  = array('in', $belong_organization_id);

            $where_and_arr[] = "b.organization_id in (".$belong_organization_id.")";
        } else {
            $where["b.organization_id"] = $organization_id;

            $where_and_arr[] = "b.organization_id = ".$organization_id;
        }
        if (count($map) > 0) {
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
        }

        if ($data_cycle != "") {
            $search_date = explode('/', $data_cycle);
            $begin_date = $search_date[0];
            $end_date = $search_date[1];

            $where['DATE_FORMAT(a.datetime, "%Y-%m-%d")'] = array(array('egt', $begin_date), array('elt',$end_date));

            $where_and_arr[] = "DATE_FORMAT(a.datetime, \"%Y-%m-%d\") >= '".$begin_date."' and DATE_FORMAT(a.datetime, \"%Y-%m-%d\") <= '".$end_date."'";
        }

        $where_and_arr[] = "DATE_FORMAT(b.datetime, \"%Y-%m-%d %H:%i:%s\") <= DATE_FORMAT(\"".date('Y-m-d H:i:s')."\", \"%Y-%m-%d %H:%i:%s\")";

        $where['DATE_FORMAT(b.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")');

		
		if (!empty($sortKey) && !empty($sort)) {
            if ($sortKey == "recharge") {
                $order = "(a.recharge-a.withdrawals)"." ".$sort;
            } else {
                $order = 'a.'.$sortKey.' '.$sort;
            }
        } else {
            $order = 'a.datetime desc';
        }
		
        $list = UserApi::getList($where, $left, $page_num, $page_size, $field, $order);
        /*for ($i=0; $i<count($list); $i++) {
            $list[$i]["nick_name"] = Utils::userTextDecode($list[$i]["nick_name"]);

            $model = M();
            $sum_field = "(ifnull(sum(if(type=1, money, 0)),0)-ifnull(sum(if(type=2, money, 0)),0)) recharge";
            $sum = $model->table('fs_recharge_withdrawals a')
                ->field($sum_field)
                ->where(array("audit_state"=>1, "user_id"=>$list[$i]["id"]))
                ->select();
            $list[$i]['recharge'] = $sum[0]["recharge"];
        }*/

        $where_str = "";
        if (count($where_and_arr) > 0 || count($where_or_arr) > 0) {
            $where_str = " where ";
            if (count($where_and_arr) > 0) {
                $where_str .= implode(" and ", $where_and_arr);
            }
            if (count($where_or_arr) > 0) {
                if (count($where_and_arr) > 0) {
                    $where_str .= " and ";
                }
                $where_str .= "(".implode(" or ", $where_or_arr).")";
            }
        }

        $model = M();
        $sql = "select count(t.id) total from (select a.id from fs_user a";
        $sql .= " left join fs_user_belong b on b.user_id = a.id and b.state=1";
        $sql .= " left join fs_agent agent on agent.id = a.recommend_id";
        $sql .= $where_str; // " where a.state != 0 and ub.organization_id = 1 group by a.order_no";
        $sql .= " group by a.id) t";
        $total = $model->query($sql);

        // $total = UserApi::getTotal($where, $left);
        $user_list = pageHelper($page_size, $page_num, $list, $total[0]['total']);
        $rel['data'] = $user_list;

        /*$model = M();
        $sum_field = "(ifnull(sum(if(type=1, money, 0)),0)-ifnull(sum(if(type=2, money, 0)),0)) recharge";
        $sum = $model->table('fs_recharge_withdrawals a')
            ->field($sum_field)
            ->where(array("audit_state"=>1))
            ->select();
        $rel['total_recharge'] = sprintf("%.2f", $sum[0]["recharge"]);*/

        // $user_list['setting'] = $AGENTCONFIG[$level]['setting'];
        // $user_list['type'] = $AGENTCONFIG[$level]['type'];
        /*$total_balance = UserApi::getSum($where, "a.balance", $left);
        if(empty($total_balance)) {
            $total_balance = 0;
        }
        $rel["total_balance"] = sprintf("%.2f", $total_balance);*/
		
		$model = M();
        $sql = "select sum(t.balance) total_balance from (select a.balance from fs_user a";
        $sql .= " left join fs_user_belong b on b.user_id = a.id and b.state=1";
        $sql .= " left join fs_agent agent on agent.id = a.recommend_id";
        $sql .= $where_str; // " where a.state != 0 and ub.organization_id = 1 group by a.order_no";
        $sql .= " group by a.id) t";
        $total_balance = $model->query($sql);

        $rel["total_balance"] = sprintf("%.2f", $total_balance[0]['total_balance']);

        $left .= " left join fs_recharge_withdrawals c on c.user_id = a.id";
        $where['c.audit_state'] = 1;
        $total_recharge = UserApi::getListAllByCondition($where, $left, "(ifnull(sum(if(c.type=1, c.money, 0)),0)-ifnull(sum(if(c.type=2, c.money, 0)),0)) recharge");

        // var_dump($total_recharge);
        $rel["total_recharge"] = sprintf("%.2f", $total_recharge[0]["recharge"]);
		
		$sql = "select (ifnull(sum(if(t.type=1, t.money, 0)),0)-ifnull(sum(if(t.type=2, t.money, 0)),0)) total_recharge from (select c.type, c.money from fs_user a";
        $sql .= " left join fs_user_belong b on b.user_id = a.id and b.state=1";
        $sql .= " left join fs_agent agent on agent.id = a.recommend_id";
        $sql .= " left join fs_recharge_withdrawals c on c.user_id = a.id";
        $sql .= $where_str; // " where a.state != 0 and ub.organization_id = 1 group by a.order_no";
        $sql .= " group by a.id) t";
        $total_recharge = $model->query($sql);

        // var_dump($total_recharge);
        $rel["total_recharge"] = sprintf("%.2f", $total_recharge[0]["total_recharge"]);

        $this->ajaxReturn($rel);
    }

    // 获取用户信息
    public function getUserInfo() {
        $user_id = $_POST['id'];
        $user = UserApi::getInfo(array("id"=>$user_id));
        $this->ajaxReturn($user);
    }

    // 删除用户
    public function delete() {
        $data['code'] = 0;
        $this->ajaxReturn($data);
    }

    // 重置用户密码
    public function resetPass() {
        $data['password'] = md5("123456");
        $map["id"] = $_POST['id'];
        UserApi::saveByCondition($map, $data);
        $ajaxdata['code'] = 1;
        $ajaxdata['msg'] = '重置密码成功，重置后密码为：123456';
        $this->ajaxReturn($ajaxdata);
    }

    // 修改用户状态
    public function changeState() {
        $model = M($this->modelName);
        $this->ajaxReturn(UserApi::save($model->create($_POST, Model::MODEL_UPDATE)));
    }

    // 更改用户归属
    public function changeBelong() {
        $org_level = $_POST['org_level'];
        $org_id = $_POST['org_id'];
        $agent_id = $_POST['agent_id'];
        $id = $_POST["user_id"];
        $data["state"] = 2;
        UserBelongApi::saveByCondition(array("user_id"=>$id, "organization_level"=>$org_level), $data);
        $agentBelong["user_id"] = $id;
        $agentBelong["organization_id"] = $org_id;
        $agentBelong["organization_level"] = $org_level;
        $agentBelong["state"] = 1;
        $agentBelong["datetime"] = date("Y-m-d H:i:s");
        UserBelongApi::add($agentBelong);
        UserApi::saveByCondition(array("id"=>$id), array("recommend_id"=>$agent_id));
        $rel['code'] = 1;
        $this->ajaxReturn($rel);
    }

    // 用户详细信息页面
    public function info() {
        // $user = UserApi::getInfo(array("id"=>$_GET['id']));

        /*$total_gain_money = OrderApi::getTotalGainMoney($_GET['id'], $user['agent_level'], 'all');
        $user['total_gain_money'] = $total_gain_money;

        $model = M();
        $map['a.user_id'] = $_GET['id'];
        $map['a.state'] = 2;
        $map['DATE_FORMAT(a.start_date, "%Y-%m-%d")'] = array('elt', date('Y-m-d'));
        $map['DATE_FORMAT(a.end_date, "%Y-%m-%d")'] = array('egt', date('Y-m-d'));
        $voucher_num = $model->table('fs_voucher a')
            ->where($map)
            ->count("a.id");

        $user['voucher_num'] = $voucher_num;

        $modelObj = M('Sys');
        $data = $modelObj->field("qrcode_url")->where(array('id' => 1))->find();
        $url = $data['qrcode_url'].$user['code'];
        $user['yaoqing_url'] = $url;

        $modelObj = M("Game_type");
        $list = $modelObj->where(array("state"=>1))->select();
        if (!empty($list) && count($list) > 0) {
            $this->assign('games',$list);
        }

        $modelObj = M("VoucherType");
        $list = $modelObj->select();
        if (!empty($list) && count($list) > 0) {
            $this->assign('voucher_type_list',$list);
        }

        $parentUser = UserApi::getUserInfo($user['agent_id']);
        $this->assign('parentData', $parentUser);

        $inviteUser = UserApi::getUserInfo($user['pid']);
        $this->assign('inviteUser', $inviteUser);*/

        // $inviteUser = UserApi::getInfo(array("id"=>$user['pid']));
        // $user['inviteUser'] = $inviteUser;

        // $this->assign('user', $user);

        $this->assign('id', $_GET['id']);
        $this->display();
    }

    // 获取用户详细信息
    public function toinfo() {
        $left = "left join fs_agent b on b.id = a.recommend_id";
        $left .= " left join fs_agent c on c.id = a.agent_id";
        $user = UserApi::getInfoByCondition(array("a.id"=>$_POST['user_id']), $left, "a.*, b.name as recommend_name, c.settlement_money, c.balance as agent_balance");

        $total_gain_money = OrderApi::getTotalGainMoneyByUserId($_POST['user_id']);
        $user['total_gain_money'] = sprintf("%.2f", $total_gain_money);

        $AGENTCONFIG = C('AGENTCONFIG');

        $user['tabs'] = $AGENTCONFIG[5]['tabs'];
        $rel['currentView'] = $AGENTCONFIG[5]['tabs'][0]['view'];
        $rel['user'] = $user;
        $rel['config'] = $AGENTCONFIG[session('admin_level')]['config'];
        $this->ajaxReturn($rel);
    }

    // 用户充值
    public function capital_adjuste() {
        $money = 0;
        $user_id = $_POST['id'];
        if (!empty($_POST['balance']) && $_POST['balance'] > 0) {
            $money = $_POST['balance'];
        }
        $type = $_POST['type'];
        $remark = $_POST['remark'];

        if (empty($remark)) {
            $remark = "资金调整";
        }

        $user = UserApi::getInfo(array('id'=>$user_id), 'balance');
        if ($type == 1) {
            $user['id'] = $user_id;
            $user['balance'] = array('exp','balance+'.$money);
            UserApi::save($user);

            $user = UserApi::getInfo(array("id"=>$user_id), "balance");
            $out_trade_no = date('YmdHi').$user_id.rand_number(1, 999);

            // 添加充值记录
            $rechargeWithdrawals = array("user_id"=>$user_id, "out_trade_no"=>$out_trade_no, "source"=>1, "money"=>$money, "type"=>1,
                "state"=>1, "remark"=>$remark, "datetime"=>date('Y-m-d H:i:s'));
            RechargeWithdrawalsApi::add($rechargeWithdrawals);

            // 添加资金流水
            $tradeDetail = array("user_id"=>$user_id, "deal_user_id"=>0, "out_trade_no"=>"$out_trade_no", "type"=>5,
                "money"=>$money, "fee_money"=>0, "other_money"=>0,"balance"=>$user['balance'],
                "source"=>6,"state"=>1, "datetime"=>date('Y-m-d H:i:s'));
            TradeDetailApi::add($tradeDetail);

            $ajaxdata['money'] = UserApi::getInfo(array('id'=>$user_id), 'balance')['balance'];
            $ajaxdata['code'] = 0;
            $ajaxdata['msg'] = '操作用户资金成功，本次增加用户资金'.$money.'元';
        } else {
            if ($user['balance'] >= $money) {
                $user['id'] = $user_id;
                $user['balance'] = array('exp','balance-'.$money);
                UserApi::save($user);

                $user = UserApi::getInfo(array("id"=>$user_id), "balance");
                $out_trade_no = date('YmdHi').$user_id.rand_number(1, 999);
                // 添加提现记录
                $rechargeWithdrawals = array("user_id"=>$user_id, "out_trade_no"=>$out_trade_no, "source"=>1, "money"=>$money, "type"=>2,
                    "state"=>1, "audit_state"=>1, "remark"=>$remark, "datetime"=>date('Y-m-d H:i:s'));
                RechargeWithdrawalsApi::add($rechargeWithdrawals);


                // 添加资金流水
                $tradeDetail = array("user_id"=>$user_id, "deal_user_id"=>0, "out_trade_no"=>"$out_trade_no", "type"=>7,
                    "money"=>-$money, "fee_money"=>0, "other_money"=>0,"balance"=>$user['balance'],
                    "source"=>6,"state"=>1, "datetime"=>date('Y-m-d H:i:s'));
                TradeDetailApi::add($tradeDetail);

                // 添加资金流水
                /*$tradeDetail = array("user_id"=>$user_id, "deal_user_id"=>0, "out_trade_no"=>"$out_trade_no", "type"=>5,
                    "money"=>$money, "fee_money"=>0, "other_money"=>0,"balance"=>$user['balance'],
                    "source"=>6,"state"=>1, "datetime"=>date('Y-m-d H:i:s'));
                TradeDetailApi::add($tradeDetail);*/


                $ajaxdata['money'] = UserApi::getInfo(array('id'=>$user_id), 'balance')['balance'];
                $ajaxdata['code'] = 0;
                $ajaxdata['msg'] = '操作用户资金成功，本次扣除用户资金'.$money.'元';
            } else {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '操作用户资金失败，用户资金不足';
            }
        }

        $this->ajaxReturn($ajaxdata);
    }

    // 用户订单列表
    public function toOrderList() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        $keyword = $_POST['keyword'];
        $type = $_POST['type'];
        $user_id = $_POST['user_id'];
        $data_cycle = $_POST['data_cycle'];

        $search_date = explode('/', $data_cycle);
        $begin_date = $search_date[0];
        $end_date = $search_date[1];

        $where = array();
        if ($keyword <> "") {
            $where['a.order_no'] = array('like', '%'.$keyword.'%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }

        if ($type == 1) {
            $map['a.state'] = 0;
        } else {
            $map['a.state'] = array("gt", 0);
        }
        $map["a.user_id"] = $user_id;
        $map['DATE_FORMAT(a.begin_time, "%Y-%m-%d")'] = array(array('egt', $begin_date), array('elt',$end_date));

        $field = 'a.*, nick_name, b.mobile_phone, c.money, c.fee_money, c.type as t_type, c.datetime';

        $left = 'left join fs_user b on b.id = a.user_id';
        $left .= ' left join fs_trade_detail c on c.out_trade_no = a.order_no and (c.type = 2 or c.type = 3 or c.type = 4)';
        // $left .= ' left join fs_user_belong ub on ub.user_id = b.id and DATE_FORMAT(ub.datetime, "%Y-%m-%d %H:%i:%s") <= DATE_FORMAT(a.begin_time, "%Y-%m-%d %H:%i:%s") and ub.organization_id = '.$organization_id;
        // $left .= ' left join fs_user_belong uub on uub.user_id = b.id and DATE_FORMAT(uub.datetime, "%Y-%m-%d %H:%i:%s") <= DATE_FORMAT(a.begin_time, "%Y-%m-%d %H:%i:%s") and uub.organization_level = 1';
        // $left .= ' left join fs_organization o on o.id = uub.organization_id';
        // $left .= ' left join fs_agent agent on agent.id = b.recommend_id';

        $group = 'a.order_no';

        $order = 'a.begin_time desc';
        $list = OrderApi::getList($map, $left, $page_num, $page_size, $field, $order, $group);
        $total = OrderApi::getTotal($map);

        $data = pageHelper($page_size, $page_num, $list, $total);

        $rel['data'] = $data;
        $this->ajaxReturn($rel);
    }

    // 用户出入金记录列表
    public function toRechargeOrWithdrawals() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        $user_id = $_POST['user_id'];
        $data_cycle = $_POST['data_cycle'];

        $search_date = explode('/', $data_cycle);
        $begin_date = $search_date[0];
        $end_date = $search_date[1];

        $map["user_id"] = $user_id;
        $map['DATE_FORMAT(datetime, "%Y-%m-%d")'] = array(array('egt', $begin_date), array('elt',$end_date));
        $list = RechargeWithdrawalsApi::getList($map, '', $field = "*", $page_num, $page_size, $order='datetime desc');
        $total = RechargeWithdrawalsApi::getTotal($map);

        $data = pageHelper($page_size, $page_num, $list, $total);
        $rel['data'] = $data;
        $this->ajaxReturn($rel);
    }

    // 用户资金流水
    public function toTradeDetailList() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        $user_id = $_POST['user_id'];
        $data_cycle = $_POST['data_cycle'];

        $search_date = explode('/', $data_cycle);
        $begin_date = $search_date[0];
        $end_date = $search_date[1];

        $map["user_id"] = $user_id;
        $map['DATE_FORMAT(datetime, "%Y-%m-%d")'] = array(array('egt', $begin_date), array('elt',$end_date));
        $list = TradeDetailApi::getList($map, $page_num, $page_size,  $field = "*", $order='datetime desc');
        $total = TradeDetailApi::getTotal($map);

        $data = pageHelper($page_size, $page_num, $list, $total);
        $rel['data'] = $data;
        $this->ajaxReturn($rel);
    }

    public function exportexcel() {
        //引入PHPExcel库文件
        // Vendor('PHPExcel.Classes.PHPExcel');

        $data_cycle = $_GET['data_cycle'];
        $nick_name = $_GET['nick_name'];
        $mobile_phone = $_GET['mobile_phone'];
        $agent_id = $_GET['agent_id'];
        $belong_organization_id = $_GET['organization_id'];


        //表格数组
        $users = $this->getData($data_cycle,$nick_name, $mobile_phone, $agent_id, $belong_organization_id);
        $data = array();
        for ($i=0; $i<count($users); $i++) {
            $user = array(
                ($i+1), $users[$i]["nick_name"], $users[$i]["mobile_phone"],$users[$i]["operation_center"],$users[$i]["member_unit"],$users[$i]["micro_ring"],
                $users[$i]["agent_name"],$users[$i]["balance"],$users[$i]["datetime"],$users[$i]["login_ip"],$users[$i]["last_login"]
            );

            array_push($data, $user);
        }

        import("Org.Util.PHPExcel");
        //创建对象
        $excel = new \PHPExcel();
        //Excel表格式,这里简略写了8列
        $letter = array('A','B','C','D','E','F','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        //表头数组
        $tableheader = array('#','昵称','手机号码', '所属运营中心', '所属会员单位', '所属微圈', '所属经纪人', '可用资金', '注册时间', '最后登录IP', '最后登录时间');
        //填充表头信息
        for($i = 0;$i < count($tableheader);$i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
        }
        //填充表格信息
        for ($i = 2;$i <= count($data) + 1;$i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key=>$value) {
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $j++;
            }
        }

        $fileName = "users";
        $date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";
        $fileName = iconv("utf-8", "gb2312", $fileName);

        //创建Excel输入对象
        $write = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="'.$fileName.'"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
    }

    private function getData($data_cycle,$nick_name,$mobile_phone,$agent_id,$belong_organization_id) {

        $organization_id = session('admin_id');
        // $level = 0;
        $field = "a.id, a.nick_name, a.mobile_phone, a.balance, a.state, a.login_ip, a.last_login, a.datetime, agent.name as agent_name";

        $left = 'left join fs_user_belong b on b.user_id = a.id';
        $left .= ' left join fs_agent agent on agent.id = a.recommend_id';
        $AGENTCONFIG = C('AGENTCONFIG');
        for($i=1; $i<(count($AGENTCONFIG)-2); $i++) {
            $field .= ', o'.$i.'.name as '.$AGENTCONFIG[$i]['field'];
            $left .= ' left join fs_user_belong ob'.$i.' on ob'.$i.'.user_id = a.id and ob'.$i.'.organization_level = '.$i;
            $left .= ' left join fs_organization o'.$i.' on o'.$i.'.id = ob'.$i.'.organization_id';
        }


        $map = array();

        if ($nick_name != "") {
            $map['a.nick_name']  = array('like', '%'.$nick_name.'%');
        }
        if ($mobile_phone != "") {
            $map['a.mobile_phone']  = array('like', '%'.$mobile_phone.'%');
        }

        if ($agent_id > 0) {
            $map['a.recommend_id']  = array('eq', $agent_id);
        } else if ($belong_organization_id != '') {
            $map['b.organization_id']  = array('in', $belong_organization_id);
        } else {
            $where["b.organization_id"] = $organization_id;
        }
        if (count($map) > 0) {
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
        }

        if ($data_cycle != "") {
            $search_date = explode('/', $data_cycle);
            $begin_date = $search_date[0];
            $end_date = $search_date[1];

            $where['DATE_FORMAT(a.datetime, "%Y-%m-%d")'] = array(array('egt', $begin_date), array('elt',$end_date));
        }

        $where['DATE_FORMAT(b.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")');
        $list = UserApi::getListAllByCondition($where, $left, $field, 'a.datetime desc', 'a.id');
        return $list;
    }

}